package com.example.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.JwtInterceptor;
import com.example.common.JwtTokenUtils;
import com.example.entity.Devices;
import com.example.entity.Params;
import com.example.entity.Users;
import com.example.exception.CustomException;
import com.example.repository.DevicesMapper;
import com.example.repository.UserDeviceMapper;
import com.example.repository.UsersMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UsersService extends ServiceImpl<UsersMapper, Users> {

    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private UserDeviceMapper userDeviceMapper;
    @Resource
    private DevicesMapper devicesMapper;

    @Resource
    private DevicesService devicesService;

    public void addUser(Users users) {
        //进行判断，查看数据表中是否已经存在该用户（相同identity相同userName）
        Users user = usersMapper.findUserByIdentityAndUsername(users.getIdentity(), users.getUserName());
        //如果该用户存在,提示前台不允许插入
        if (user != null) {
            throw new CustomException("该用户已存在，请勿重复操作！");
        }
        //用户名不能为空，已在数据库实现
        if (users.getUserName() == null || "".equals(users.getUserName())) {
            throw new CustomException("用户名不能为空！");
        }
        //用户身份不能为空
        if (users.getIdentity() == null) {
            throw new CustomException("请选择您的身份！");
        }
        usersMapper.addUser(users);
    }

    public void deleteUser(long userId) {
        usersMapper.deleteById(userId);
    }

    //修改方法类型和返回值类型，改为带有分页信息的类型
    public PageInfo<Users> findBySearchOfUsers(Params params) {
        //开启分页
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<Users> search = usersMapper.findBySearchOfUsers(params);
        return PageInfo.of(search);
    }

    public void updateUser(Users users) {
        usersMapper.updateById(users);
    }

    public Users login(Users users) {
        //1.进行非空判断
        //用户身份不能为空
        if (users.getIdentity() == null || "".equals(users.getIdentity())) {
            throw new CustomException("请选择您的身份！");
        }
        //用户名不能为空
        if (users.getUserName() == null || "".equals(users.getUserName())) {
            throw new CustomException("用户名不能为空！");
        }
        //用户密码不能为空
        if (users.getPassword() == null || "".equals(users.getPassword())) {
            throw new CustomException("请输入密码！");
        }
        //2.从数据库里根据身份，用户名，密码查询对应用户
        // 查询成功，允许登录
        Users user = usersMapper.findUserByIdentityAndUsernameAndPassword(users.getIdentity(), users.getUserName(), users.getPassword());
        //查询失败，不允许登录
        if (user == null) {
            throw new CustomException("用户名或密码错误!");
        }
        //生成登录用户对应用的token，然后跟着user一起返回给前台
        String token = JwtTokenUtils.genToken(user.getUserId().toString(), user.getPassword());
        user.setToken(token);
        List<String> deviceIds = userDeviceMapper.selectDeviceIdsByUserId(user.getUserId());
        String[] deviceIdArray = deviceIds.toArray(new String[0]);
        user.setDeviceIds(deviceIdArray);
        return user;
    }

    //JWT拦截器通过解码token获取userId，查看用户是否合法
    public Users findById(Integer userId) {
        return usersMapper.selectById(userId);
    }

    public void updateUserDevices(Long userId, List<String> deviceIds) {
        log.info("被操作人：" + userId + ",可查看设备的deviceId：" + deviceIds);
        if (userId == null || deviceIds == null || deviceIds.isEmpty()) {
            return;
        }
        //删除旧的设备权限
        userDeviceMapper.deleteExistDevicesByUserId(userId);
        log.info("旧设备已删除成功，开始根据前端传过来的deviceIds数组插入新设备");

        // 使用 ArrayList 来动态存储设备名称
        List<String> deviceNames = new ArrayList<>(deviceIds.size());

        //遍历deviceIds数组，查找对应的设备，并修改user_device表
        for (int i = 0; i < deviceIds.size(); i++) {
            String deviceId = deviceIds.get(i);
            //若deviceId非空
            if (deviceId != null) {
                // 查询设备名称，确保不为空
                Devices device = devicesMapper.selectById(deviceId);
                if (device != null) {
                    userDeviceMapper.insertUserDevice(userId, deviceId, devicesService.getDeviceNameById(deviceId));
                    deviceNames.add(devicesService.getDeviceNameById(deviceId));
                }
            }
        }
        log.info("新设备插入成功：" + deviceNames);
    }

    public void deleteBatch(List<Users> list) {
        usersMapper.deleteBatchIds(list);
    }

    public List<Users> findAll() {
        return usersMapper.selectList(null);
    }
}
